package com.lhsy.djcloud.config;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.lhsy.djcloud.common.ReturnT;
import com.lhsy.djcloud.common.SecurityConstant;
import com.lhsy.djcloud.entity.dto.UserDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 登陆拦截器
 * @author wangzw
 */
@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        httpServletResponse.setHeader("Access-Control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));
        httpServletResponse.setHeader("Access-Control-Allow-Credentials","true");
        // 跨域时会首先发送一个option请求，这里我们给option请求直接返回正常状态
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(HttpStatus.OK.value());
            return false;
        }
        if (httpServletRequest.getServletPath().startsWith("/error")){
            returnJson(httpServletResponse,JSONUtil.toJsonStr(ReturnT.FAIL(ReturnT.FAIL_CODE,"系统异常")));
            return false;
        }
        if (httpServletRequest.getServletPath().startsWith("/login")
                || httpServletRequest.getServletPath().startsWith("/tenant/register")
                || httpServletRequest.getServletPath().startsWith("/upload")
                || httpServletRequest.getServletPath().startsWith("/down")
                || httpServletRequest.getServletPath().startsWith("/sign")
                ){
            return true;
        }
        //判断登录状态
        String token = httpServletRequest.getHeader(SecurityConstant.HEADER);
        if (StrUtil.isEmpty(token)){
            returnJson(httpServletResponse,JSONUtil.toJsonStr(ReturnT.FAIL(ReturnT.FAIL_401,"登陆信息失效,请重新登陆")));
            return false;
        }
        String user = redisTemplate.opsForValue().get(SecurityConstant.TOKEN__USER_PRE +token);
        //当前用户未登录或者登陆已经失效
        if (StrUtil.isEmpty(user)){
            returnJson(httpServletResponse,JSONUtil.toJsonStr(ReturnT.FAIL(ReturnT.FAIL_401,"您已被其他人踢出")));
            return false;
        }
        UserDto userDto = JSONUtil.toBean(user, UserDto.class);
        log.info("用户请求:user[{}],token[{}],请求路径[{}]",userDto.getUserName(),token,httpServletRequest.getServletPath());
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
    }

    private void returnJson(HttpServletResponse response, String json) throws Exception{
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(json);
        } catch (IOException e) {

        } finally {
            if (writer != null){
                writer.close();
            }
        }
    }
}
